package com.wans.guli.integration.sms;

import com.wans.guli.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Controller
@Slf4j
public class SMSController {

    @Autowired
    private SMSThirdAPIClient smsThirdAPIClient;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/sms/sendCode")
    @ResponseBody
    public R sendCode(@RequestParam("phone") String phone, @RequestParam("code") String code) {
        HashMap<String, String> params = new HashMap<>();
        params.put("mobile", phone);
        params.put("param", String.format("**code**:%s,**minute**:15", code));

        //smsSignId（短信前缀）和templateId（短信模板），可登录国阳云控制台自助申请。参考文档：http://help.guoyangyun.com/Problem/Qm.html
        params.put("smsSignId", "2e65b1bb3d054466b82f0c9d125465e2");
        params.put("templateId", "908e94ccf08b4476ba6c876d13f084ad");

        String authorization = "APPCODE 769f39706ab342c1883efb63938803e9";

        // TODO 验证码防刷
        Boolean exist = stringRedisTemplate.opsForValue().setIfAbsent("sms:code:verify:" + phone, "exist", 1, TimeUnit.MINUTES);
        if (exist == null || !exist) return R.error("请勿重复发送验证码");

        String resultMap = smsThirdAPIClient.sendSms(params, authorization);

        log.info("发送短信结果：{}", resultMap);

        return R.success(resultMap);
    }
}
